﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using Memcached.ClientLibrary;

namespace olierFrm.GeneralCache
{
 internal static class MemcachedClientService
{
    // Nested Types
    public static class Instance
    {
        
        private static string[] _CacheServerlist;
        private static MemcachedClient _Memcached;
        private static string _PoolName;

        
        private static void init()
        {
            SockIOPool pool = SockIOPool.GetInstance(PoolName);
            pool.SetServers(CacheServerlist);
            pool.InitConnections = 3;
            pool.MinConnections = 3;
            pool.MaxConnections = 5;
            pool.SocketConnectTimeout = 0x3e8;
            pool.SocketTimeout = 0xbb8;
            pool.MaintenanceSleep = 30L;
            pool.Failover = true;
            pool.Nagle = false;
            pool.Initialize();
            _Memcached = new MemcachedClient();
            _Memcached.PoolName = PoolName;
            _Memcached.EnableCompression = false;
        }

        
        private static string[] CacheServerlist
        {
            get
            {
                if (ConfigurationManager.AppSettings["Memcached"] == null)
                {
                    throw new Exception("在 Web.config 中 appSettings 节点没有找到 Memcached，或格式错误\r\n <add key=\"Memcached\" value=\"127.0.0.1:11211;192.168.39.108:11211\"/>");
                }
                if (_CacheServerlist == null)
                {
                    _CacheServerlist = ConfigurationManager.AppSettings["Memcached"].Split(new char[] { ';' });
                }
                return _CacheServerlist;
            }
        }

        public static MemcachedClient Client
        {
            get
            {
                if (_Memcached == null)
                {
                    init();
                }
                return _Memcached;
            }
        }

        private static string PoolName
        {
            get
            {
                if (ConfigurationManager.AppSettings["MemcachedPoolName"] == null)
                {
                    throw new Exception("在 Web.config 中 appSettings 节点没有找到 MemcachedPoolName，或格式错误\r\n <add key=\"MemcachedPoolName\" value=\"WebForm\"/>");
                }
                if (_PoolName == null)
                {
                    _PoolName = ConfigurationManager.AppSettings["MemcachedPoolName"];
                }
                return _PoolName;
            }
        }
    }
}

 

}
